#include "protocol.h"
#include <unistd.h>
#include <string.h>

int send_message(int socket, Message* msg) {
    // 添加消息长度前缀
    size_t total_size = sizeof(Message);
    ssize_t bytes_sent = write(socket, &total_size, sizeof(size_t));
    if (bytes_sent != sizeof(size_t)) {
        return -1;
    }
    
    // 发送消息内容
    bytes_sent = write(socket, msg, sizeof(Message));
    if (bytes_sent != sizeof(Message)) {
        return -1;
    }
    
    return 0;
}

int receive_message(int socket, Message* msg) {
    // 接收消息长度
    size_t total_size;
    ssize_t bytes_received = read(socket, &total_size, sizeof(size_t));
    if (bytes_received != sizeof(size_t)) {
        return -1;
    }
    
    // 接收消息内容
    bytes_received = read(socket, msg, sizeof(Message));
    if (bytes_received != sizeof(Message)) {
        return -1;
    }
    
    return bytes_received;
}
